<template>
  <div>
    <el-row>
      <el-col>
        <my-form
          :formOptions="findFormOptions"
          :isInline="true"
          :isSearch="true"
          @sureSubmit="findTableData"
        >
          <template #bottom_button>
            <el-button
              size="mini"
              @click="reset"
              icon="el-icon-refresh"
              type="primary"
              >重置</el-button
            >
          </template>
        </my-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end" style="margin-bottom:10px">
      <el-col :span="10">
        <el-button size="mini" @click="add" icon="el-icon-circle-plus" type="primary"
          >新增用户</el-button
        >
        <el-upload
          class="upload-demo"
          ref="excelUpload"
          action="http://localhost:8080/api/UserManage/uploadExcel"
          :before-upload="onBeforeUpload"
          :on-success="uploadSuccess"
          :show-file-list="false"
        >
          <el-button icon="el-icon-upload" type="primary" size="mini">导入表格</el-button>
        </el-upload>
         <el-button size="mini" icon="el-icon-download" type="primary" @click="downloadExample"
          >下载导入样例xlsx表格</el-button
        >
        <el-button size="mini" icon="el-icon-download" type="primary" @click="downloadExcel"
          >导出表格</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <my-table
          :tableData="tableData"
          :tableColumnOptions="tableColumnOptions"
          :hasBorder="true"
          :hasStripe="true"
          :hasIndex="true"
          :hasSelection="true"
          @selectionChange="selectionChange"
        >
          <template #userResdire="{ data }">
            <span class="userResdire">{{ data.sciUser.userResdire }}</span>
          </template>
          <template #userAge="{ data }">
            <span class="userResdire">{{
               (data.sciUser.userAge + "").slice(0, 10)
            }}</span>
          </template>

          <template #userStudy="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userStudy)
            }}</span>
          </template>
          <template #userSciunit="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userSciunit)
            }}</span>
          </template>
          <template #userEndstudy="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userEndstudy)
            }}</span>
          </template>
          <template #userPersunit="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userPersunit)
            }}</span>
          </template>
          <template #userSeccate="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userSeccate)
            }}</span>
          </template>
          <template #userCatego="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userCatego)
            }}</span>
          </template>
          <template #userFircate="{ data }">
            <span class="userResdire">{{
              (data.sciUser.userFircate)
            }}</span>
          </template>
          <!-- <template #rootName="{ data }">
            <span class="rootName">{{
              rootDisplay(data)
            }}</span>
          </template> -->
          <template #operation="{ data }">
            <el-button type="text" @click="update(data.sciUser)"
              >编辑</el-button
            >
            <el-button type="text" @click="remove(data.sciUser)"
              >删除</el-button
            >
            <el-popconfirm
              v-show="nowRoot=='学科带头人'?false:true"
              confirm-button-text="添加权限"
              cancel-button-text="删除权限"
              confirm-button-type="success"
              cancel-button-type="danger"
              @confirm="root_T(data.sciUser)"
              @cancel="root_S(data.sciUser)"
              icon="el-icon-info"
              icon-color="red"
              title="请选择操作"
            >
              <el-button slot="reference" type="text">修改权限</el-button>
            </el-popconfirm>
            <el-button type="text" @click="changePwd(data.sciUser)"
              >修改密码</el-button
            >
          </template>
        </my-table>
      </el-col>
    </el-row>
    <my-dialog :title="userTitle" :dialogVisible.sync="userDialog">
      <template #content>
        <my-form
          :formOptions="addFormOptions"
          :rules="addFormRules"
          :form="isAddUser ? copyForm : form"
          @sureSubmit="userSubmit"
        ></my-form>
      </template>
    </my-dialog>
    <my-dialog :title="rootTitle" :dialogVisible.sync="rootDialog">
      <template #content>
        <my-form
          :formOptions="rootFormOptions"
          @sureSubmit="rootSubmit"
        ></my-form>
      </template>
    </my-dialog>
    <my-dialog :title="passwordTitle" :dialogVisible.sync="passwordDialog">
      <template #content>
        <my-form
          :formOptions="passwordOptions"
          :rules="passwordRules"
          @sureSubmit="surePasswordSubmit"
        ></my-form>
      </template>
    </my-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import cloneDeep from "lodash/cloneDeep";
import { getSlide } from "@/api/user/myInfo";
import { changePassword } from "@/api/user/myAccount";
import {getModelByLabel,projectCate} from "@/utils/metaInfo"
import {
  A_tableData,
  A_add,
  A_update,
  A_remove,
  A_addRoot,
  A_removeRoot,
  A_downLoadExcel,
  A_downLoadExample,
} from "@/api/user/userMange";
import {
  E_beforeUpload,
  E_uploadSuccess,
  E_downloadExcel,
} from "@/utils/aboutExcel";
import myForm from "@/components/myForm.vue";
import myTable from "@/components/myTable.vue";
import myDialog from "@/components/myDialog.vue";
import { mapState } from "vuex";
export default {
  name: "userInfo",
  inject: ["reload"],
  data() {
    return {
      findFormOptions: [
        {
          type: "input",
          label: "姓名",
          model: "userName",
        },
        {
          type: "input",
          label: "职称",
          model: "userProtitle",
        },
         {
          type: "input",
          label: "科研单位",
          model: "userPersunit",
        },
      ],
      tableData: [],
      tableColumnOptions: [
        {
          label: "姓名",
          prop: "sciUser.userName",
        },
        {
          isSlot: true,
          slotName: "userAge",
          label: "出生日期",
          prop: "sciUser.userAge",
        },
        {
          label: "工号",
          prop: "sciUser.userId",
        },
        {
          isSlot: true,
          slotName: "userStudy",
          label: "所在专业",
          prop: "sciUser.userStudy",
        },
        {
          label: "性别",
          prop: "sciUser.userSex",
        },
        {
          isSlot: true,
          slotName: "userEndstudy", 
          label: "毕业专业",
          prop: "sciUser.userEndstudy",
        },
        {
          label: "学历",
          prop: "sciUser.userDegree",
        },
        {
          isSlot: true,
          slotName: "userPersunit",
          label: "人事单位",
          prop: "sciUser.userPersunit",
        },
        {
          label: "学位",
          prop: "sciUser.userAcadegree",
        },
        {
          isSlot: true,
          slotName: "userSciunit",
          label: "科研单位",
          prop: "sciUser.userSciunit",
        },
        {
          label: "职称",
          prop: "sciUser.userProtitle",
        },
        {
          isSlot: true,
          slotName: "userCatego",
          label: "学科门类",
          prop: "sciUser.userCatego",
        },
        {
          label: "电话",
          prop: "sciUser.userPhone",
        },
        {
          label: "邮箱",
          prop: "sciUser.userEmail",
        },
        {
          isSlot: true,
          slotName: "userFircate",
          label: "所在学科",
          prop: "sciUser.userFircate",
        },

        {
          isSlot: true,
          slotName: "userSeccate",
          label: "学科方向",
          prop: "sciUser.userSeccate",
        },
        {
          isSlot: true,
          slotName: "userResdire",
          label: "研究方向",
          prop: "sciUser.userResdire",
        },
        {
          label: "权限",
          prop: "rootName",
        },
        {
          label: "操作",
          isSlot: true,
          slotName: "operation",
          fixed: "right",
          width: "250",
        },
      ],
      userTitle: "新增/修改",
      rootTitle: "用户权限操作",
      passwordTitle: "修改密码",
      passwordOptions: [
        {
          type: "input",
          label: "新密码",
          model: "userPassword",
        },
        {
          type: "input",
          label: "确认密码",
          model: "rePassword",
        },
      ],
      passwordRules: {
        userPassword: [{ required: true, message: "请输入密码" }],
        rePassword: [{ required: true, message: "请确认密码" }],
      },
      addFormOptions: [
        {
          type: "input",
          label: "姓名",
          model: "userName",
        },
        {
          type: "date",
          label: "出生日期",
          model: "userAge",
        },
        {
          type: "input",
          label: "工号",
          model: "userId",
        },
        {
          type: "select",
          label: "所在专业",
          model: "userStudy",
          options_type: "profeInfos",
          options: [],
        },
        {
          type: "radio",
          label: "性别",
          model: "userSex",
          width: 216,
          options: [
            {
              label: "男",
              model: "男",
            },
            {
              label: "女",
              model: "女",
            },
          ],
        },
        {
          type: "input",
          label: "毕业专业",
          model: "userEndstudy",
        },
        {
          type: "radio",
          label: "学历",
          model: "userDegree",
          options: [
            { label: "专科", model: "专科" },
            { label: "本科", model: "本科" },
            { label: "研究生", model: "研究生" },
            { label: "其他", model: "其他" },
          ],
        },
        {
          type: "radio",
          label: "学位",
          model: "userAcadegree",
          width:600,
          options: [
            { label: "学士", model: "学士" },
            { label: "研究生", model: "研究生" },
            { label: "博士", model: "博士" },
            { label: "其他", model: "其他" },
          ],
        },

        {
          type: "select",
          label: "人事单位",
          model: "userPersunit",
          options_type: "sciUtils",
          width:179,
          options: [],
        },
        {
          type: "select",
          label: "科研单位",
          model: "userSciunit",
          options_type: "sciUtils",
          options: [],
        },
        {
          type: "input",
          label: "职称",
          model: "userProtitle",
        },
        {
          type: "select",
          label: "学科门类",
          model: "userCatego",
          options: [
            {
              label:'自然科学',
              model:1,
            },
             {
              label:'人文社科',
              model:2,
            }
          ],
        },
        {
          type: "input",
          label: "电话",
          model: "userPhone",
        },
        {
          type: "select",
          label: "所在学科",
          model: "userFircate",
          options_type: "sciDiscipline",
          options: [],
        },
        {
          type: "input",
          label: "邮箱",
          model: "userEmail",
        },
        {
          type: "select",
          label: "学科方向",
          model: "userSeccate",
          options_type: "sciDirection",
          options: [],
        },
        {
          type: "textarea",
          label: "研究方向",
          model: "userResdire",
          width: 500,
        },
      ],
      addFormRules: {
        userName: [{ required: true, message: "请输入姓名" }],
        userId: [{ required: true, message: "请输入职工号" }],
        userAge: [{ required: false, message: "请选择出生日期" }],
        userStudy: [{ required: false, message: "请选择专业" }],
        userEndstudy: [{ required: false, message: "请选择毕业专业" }],
        userPersunit: [{ required: true, message: "请选择人事单位" }],
        userSciunit: [{ required: true, message: "请选择科研单位" }],
        userDept: [{ required: true, message: "请输入教研室" }],
        userDegree: [{ required: true, message: "请选择学历" }],
        userAcadegree: [{ required: true, message: "请输入学位" }],
        userProtitle: [{ required: true, message: "请输入职称" }],
        userCatego: [{ required: true, message: "请选择学科门类" }],
        userFircate: [{ required: true, message: "请选择所在学科" }],
        userSeccate: [{ required: true, message: "请选择学科方向" }],
        userResdire: [{ required: true, message: "请输入研究方向" }],
        userPhone: [{ required: false, message: "请输入电话" }],
        userEmail: [{ required: true, message: "请输入邮箱" }],
      },
      userDialog: false,
      rootDialog: false,
      passwordDialog: false,
      form: null,
      copyForm: {},
      isAddUser: false,
      isAddRoot: false,
      rootFormOptions: [
        {
          type: "radio",
          label: "请选择",
          model: "rootName",
          options: [
            {
              label: "学科带头人",
              model: "学科带头人",
            },
            {
              label: "学院管理员",
              model: "学院管理员",
              disabled:false
            },
            {
              label: "校管理员",
              model: "校管理员",
              disabled:true
            },
          ],
        },
      ],
      handleUser: null,
      multipleSelection: [],
      userId: null,
      sildeArr: [],
      arr_sciUtils: [],
      arr_sciDiscipline: [],
      arr_profeInfos: [],
    };
  },
  watch: {
    'form.userFircate': {
        handler(newVal, oldVal) {
            console.log(newVal, oldVal)
            this.getSciDisciplineOptions()
        },
        deep: true,
        immediate: true
    },
    'copyForm.userFircate': {
        handler(newVal, oldVal) {
            console.log(newVal, oldVal)
            this.getSciDisciplineOptions()
        },
        deep: true,
        immediate: true
    }
  } ,
  async created() {
    this.getTableData();
    await this.getSlides();
    this.addFormOptions.map((item) => {
      if (item.options_type) {
        if (item.options_type === "sciUtils") {
          item.options = this.sciUtils();
        } else if (item.options_type === "sciDirection") {
          item.options = this.getSciDisciplineOptions();
        } else if (item.options_type === "sciDiscipline") {
          item.options = this.sciDiscipline();
        }else if (item.options_type === "profeInfos") {
          item.options = this.profeInfos();
        }
      }
      return item;
    });
    console.log(this.nowRoot,this.nowRoot.endsWith("院管理员"))
    if(this.nowRoot === '校管理员'){
      this.rootFormOptions[0].options[this.rootFormOptions[0].options.length-1].disabled = false
    }
    if(this.nowRoot.endsWith("院管理员")){
      this.rootFormOptions[0].options[1].disabled = true
      
    }
    console.log(this.rootFormOptions[0].options[1].disabled)
  },
  components: {
    myForm,
    myTable,
    myDialog,
  },
  methods: {
    rootDisplay(rootlist){
      console.log(rootlist)
      return rootlist
    },
    async getSciDisciplineOptions(){
      let curForm = this.isAddUser? this.copyForm : this.form
      if(!curForm.userFircate){
        this.$message({ type: "error", message: "请先选择所在学科" });
        return null
      }
   
      let SciDisciplineOptions = await request({
        url: "/SciDirection/getDirection/select",
        method: "post",
        data:{
          dirDis:curForm.userFircate
        }
        })
      let arr = []
      SciDisciplineOptions.data.forEach((item) => {
        let { dirName, dirkey } = item;
        arr.push({ label: dirName, model: dirkey });
      });
      this.addFormOptions.map((item) => {
      if (item.options_type) {
         if (item.options_type === "sciDirection") {
          item.options = arr
        }
      }})
      // this.addFormOptions.sciDirection.options = SciDisciplineOptions.data
      // return SciDisciplineOptions.data
    },
    async getSlides() {
      let res = await getSlide();
      this.sildeArr = res.data;
    },
    sciUtils() {
      let arr = [];
      this.sildeArr.sciUtils.forEach((item) => {
        let { utilsName, utilsKey } = item;
        arr.push({ label: utilsName, model: utilsKey });
      });
      this.arr_sciUtils = arr;
      return arr;
    },
    sciDiscipline() {
      let arr = [];
      this.sildeArr.sciDiscipline.forEach((item) => {
        let { subName, subKey } = item;
        arr.push({ label: subName, model: subKey });
      });
      this.arr_sciDiscipline = arr;
      return arr;
    },
    profeInfos() {
      let arr = [];
      this.sildeArr.profeInfos.forEach((item) => {
        let { proName, proKey } = item;
        arr.push({ label: proName, model: proKey });
      });
      this.arr_profeInfos = arr;
      return arr;
    },
    async findTableData(data) {
      let result = await A_tableData(data);
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async getTableData() {
      let result = await A_tableData({});
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async reset() {
      let result = await A_tableData({});
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    selectionChange(data) {
      this.multipleSelection = cloneDeep(data);
    },
    add() {
      this.isAddUser = true;
      this.userDialog = true;
    },
    update(data) {
      this.isAddUser = false;
      this.form = cloneDeep(data);
      this.userDialog = true;
    },
    remove(data) {
      this.$confirm("你确定要删除该用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { userId } = data;
          let res = await A_remove(userId);
          if (res.code === 1) {
            this.$message({ type: "success", message: res.data });
            this.reload();
          } else {
            this.$message({ type: "error", message: res.msg });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async userSubmit(data) {  
      console.log(this.form,this.copyForm)
      console.log(data,this.arr_sciUtils)
      data.userPersunit = getModelByLabel(data.userPersunit,this.arr_sciUtils)
      data.userSciunit = getModelByLabel(data.userSciunit,this.arr_sciUtils)
      data.userCatego =  getModelByLabel(data.userCatego,projectCate)
      data.userStudy = getModelByLabel(data.userStudy,this.arr_profeInfos)

      if (this.isAddUser) {
        let res = await A_add(data);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        let res = await A_update(data);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      }
      this.reload();
    },
    root_T({ userKey }) {
      this.isAddRoot = true;
      this.rootDialog = true;
      this.handleUser = userKey;
    },
    root_S({ userKey }) {
      this.isAddRoot = false;
      this.rootDialog = true;
      this.handleUser = userKey;
    },
    async rootSubmit({ rootName }) {
      if (this.isAddRoot) {
        let res = await A_addRoot({
          rootName,
          userKey: this.handleUser,
        });
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
          this.rootDialog = false;
        }
      } else {
        let res = await A_removeRoot({
          rootName,
          userKey: this.handleUser,
        });
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
          this.rootDialog = false;
        }
      }
    },
    onBeforeUpload(file) {
      return E_beforeUpload(file);
    },
    uploadSuccess(res, file, flieist) {
      E_uploadSuccess(res);
      this.reload();
    },
      downloadExample() {
      A_downLoadExample().then(
        (res) => {
          const url = window.URL.createObjectURL(new Blob([res]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "导入数据样例表.xls");
          document.body.appendChild(link);
          link.click();
        },
        () => {
          this.$message({ type: "error", message: "出错了" });
        }
      );
    },
    downloadExcel() {
      if (this.multipleSelection.length > 0) {
        E_downloadExcel(this.downloadExcelData).then(
          () => {
            A_downLoadExcel().then(
              (res) => {
                const url = window.URL.createObjectURL(new Blob([res]));
                const link = document.createElement("a");
                link.href = url;
                link.setAttribute("download", "用户数据名单.xls");
                document.body.appendChild(link);
                link.click();
              },
              () => {
                this.$message({ type: "error", message: "出错了" });
              }
            );
          },
          () => {
            this.$message({ type: "error", message: "出错了" });
          }
        );
      } else {
        this.$message({ type: "warning", message: "请选择要导出的数据" });
      }
    },
    changePwd(data) {
      const { userId } = data;
      this.userId = userId;
      this.passwordDialog = true;
    },
    surePasswordSubmit({ userPassword, rePassword }) {
      if (userPassword === rePassword) {
        changePassword(this.userId, userPassword).then(
          (res) => {
            this.$message({ type: "success", message: "修改成功" });
            this.passwordDialog = false;
          },
          (err) => {
            this.$message({ type: "error", message: "修改失败" });
            this.passwordDialog = false;
          }
        );
      } else {
        this.$message({ type: "error", message: "两次密码输入不一致" });
      }
    },
    fc_arr_profeInfos(value) {
      for (var item of this.arr_profeInfos) {
        if (item.model == value) return item.label;
      }
    },
    fc_arr_sciUtils(value) {
      for (var item of this.arr_sciUtils) {
        if (item.model == value) return item.label;
      }
    },
    fc_arr_sciDiscipline(value) {
      for (var item of this.arr_sciDiscipline) {
        if (item.model == value) return item.label;
      }
    },
  },
  computed: {
    ...mapState("myInfo", ["nowRoot"]),
    downloadExcelData() {
      let arr = [];
      this.multipleSelection.forEach((item) => {
        arr.push(item.sciUser.userId);
      });
      return arr;
    },
  },
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  margin: 0 3px;
}

.userResdire {
  text-align: center;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>